import 'package:flutter/material.dart';
import '../services/media_scan_service.dart';

class FilterPanel extends StatefulWidget {
  final Function(MediaFilter) onFilterChanged;
  final MediaFilter currentFilter;

  const FilterPanel({
    super.key,
    required this.onFilterChanged,
    required this.currentFilter,
  });

  @override
  State<FilterPanel> createState() => _FilterPanelState();
}

class _FilterPanelState extends State<FilterPanel> {
  late MediaFilter _filter;

  @override
  void initState() {
    super.initState();
    _filter = widget.currentFilter.copy();
  }

  void _updateFilter() {
    widget.onFilterChanged(_filter);
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 280,
      decoration: BoxDecoration(
        color: Theme.of(context).colorScheme.surface,
        border: Border(
          right: BorderSide(color: Colors.grey[300]!),
        ),
      ),
      child: Column(
        children: [
          // 筛选标题
          Container(
            padding: const EdgeInsets.all(16.0),
            decoration: BoxDecoration(
              color: Theme.of(context).colorScheme.surfaceContainerHighest,
              border: Border(
                bottom: BorderSide(color: Colors.grey[300]!),
              ),
            ),
            child: Row(
              children: [
                const Icon(Icons.filter_list, size: 20),
                const SizedBox(width: 8),
                Text(
                  '筛选条件',
                  style: Theme.of(context).textTheme.titleMedium?.copyWith(
                    fontWeight: FontWeight.bold,
                  ),
                ),
                const Spacer(),
                TextButton(
                  onPressed: () {
                    setState(() {
                      _filter = MediaFilter();
                    });
                    _updateFilter();
                  },
                  child: const Text('清除'),
                ),
              ],
            ),
          ),
          
          // 筛选内容
          Expanded(
            child: ListView(
              padding: const EdgeInsets.all(16.0),
              children: [
                _buildMediaTypeFilter(),
                const SizedBox(height: 24),
                _buildFileExtensionFilter(),
                const SizedBox(height: 24),
                _buildPhotoParameterFilters(),
                const SizedBox(height: 24),
                _buildVideoParameterFilters(),
              ],
            ),
          ),
        ],
      ),
    );
  }

  // 媒体类型筛选
  Widget _buildMediaTypeFilter() {
    return _FilterSection(
      title: '媒体类型',
      child: Column(
        children: [
          CheckboxListTile(
            title: const Text('照片'),
            value: _filter.showImages,
            onChanged: (value) {
              setState(() {
                _filter.showImages = value ?? true;
              });
              _updateFilter();
            },
            controlAffinity: ListTileControlAffinity.leading,
            dense: true,
          ),
          CheckboxListTile(
            title: const Text('视频'),
            value: _filter.showVideos,
            onChanged: (value) {
              setState(() {
                _filter.showVideos = value ?? true;
              });
              _updateFilter();
            },
            controlAffinity: ListTileControlAffinity.leading,
            dense: true,
          ),
        ],
      ),
    );
  }

  // 文件扩展名筛选
  Widget _buildFileExtensionFilter() {
    final imageExts = MediaScanService.getSupportedImageExtensions();
    final videoExts = MediaScanService.getSupportedVideoExtensions();
    
    return _FilterSection(
      title: '文件格式',
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          if (_filter.showImages) ...[
            Text(
              '图片格式',
              style: Theme.of(context).textTheme.bodySmall?.copyWith(
                fontWeight: FontWeight.w500,
                color: Colors.grey[600],
              ),
            ),
            const SizedBox(height: 8),
            Wrap(
              spacing: 8,
              runSpacing: 8,
              children: imageExts.map((ext) => FilterChip(
                label: Text(ext.substring(1).toUpperCase()),
                selected: _filter.selectedExtensions.contains(ext),
                onSelected: (selected) {
                  setState(() {
                    if (selected) {
                      _filter.selectedExtensions.add(ext);
                    } else {
                      _filter.selectedExtensions.remove(ext);
                    }
                  });
                  _updateFilter();
                },
              )).toList(),
            ),
            const SizedBox(height: 16),
          ],
          if (_filter.showVideos) ...[
            Text(
              '视频格式',
              style: Theme.of(context).textTheme.bodySmall?.copyWith(
                fontWeight: FontWeight.w500,
                color: Colors.grey[600],
              ),
            ),
            const SizedBox(height: 8),
            Wrap(
              spacing: 8,
              runSpacing: 8,
              children: videoExts.map((ext) => FilterChip(
                label: Text(ext.substring(1).toUpperCase()),
                selected: _filter.selectedExtensions.contains(ext),
                onSelected: (selected) {
                  setState(() {
                    if (selected) {
                      _filter.selectedExtensions.add(ext);
                    } else {
                      _filter.selectedExtensions.remove(ext);
                    }
                  });
                  _updateFilter();
                },
              )).toList(),
            ),
          ],
        ],
      ),
    );
  }

  // 照片参数筛选
  Widget _buildPhotoParameterFilters() {
    if (!_filter.showImages) return const SizedBox.shrink();
    
    return _FilterSection(
      title: '照片参数',
      child: Column(
        children: [
          // 焦距筛选
          _buildRangeFilter(
            '焦距 (mm)',
            _filter.focalLengthRange,
            (range) {
              setState(() {
                _filter.focalLengthRange = range;
              });
              _updateFilter();
            },
            min: 10,
            max: 800,
          ),
          const SizedBox(height: 16),
          
          // 光圈筛选
          _buildRangeFilter(
            '光圈',
            _filter.apertureRange,
            (range) {
              setState(() {
                _filter.apertureRange = range;
              });
              _updateFilter();
            },
            min: 1.0,
            max: 32.0,
          ),
          const SizedBox(height: 16),
          
          // ISO筛选
          _buildRangeFilter(
            'ISO',
            _filter.isoRange,
            (range) {
              setState(() {
                _filter.isoRange = range;
              });
              _updateFilter();
            },
            min: 50,
            max: 102400,
          ),
        ],
      ),
    );
  }

  // 视频参数筛选
  Widget _buildVideoParameterFilters() {
    if (!_filter.showVideos) return const SizedBox.shrink();
    
    return _FilterSection(
      title: '视频参数',
      child: Column(
        children: [
          // 时长筛选
          _buildRangeFilter(
            '时长 (分钟)',
            _filter.durationRange,
            (range) {
              setState(() {
                _filter.durationRange = range;
              });
              _updateFilter();
            },
            min: 0,
            max: 300,
          ),
          const SizedBox(height: 16),
          
          // 分辨率筛选
          _buildResolutionFilter(),
        ],
      ),
    );
  }

  // 范围筛选组件
  Widget _buildRangeFilter(
    String title,
    RangeValues? currentRange,
    Function(RangeValues?) onChanged,
    {required double min, required double max}
  ) {
    final isActive = currentRange != null;
    final range = currentRange ?? RangeValues(min, max);
    
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            Checkbox(
              value: isActive,
              onChanged: (value) {
                onChanged(value == true ? RangeValues(min, max) : null);
              },
            ),
            Text(title),
            if (isActive) ...[
              const Spacer(),
              Text(
                '${range.start.toInt()} - ${range.end.toInt()}',
                style: Theme.of(context).textTheme.bodySmall,
              ),
            ],
          ],
        ),
        if (isActive)
          RangeSlider(
            values: range,
            min: min,
            max: max,
            divisions: ((max - min) / (max > 100 ? 100 : 1)).round(),
            onChanged: (values) {
              onChanged(values);
            },
          ),
      ],
    );
  }

  // 分辨率筛选
  Widget _buildResolutionFilter() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          '分辨率',
          style: Theme.of(context).textTheme.bodyMedium?.copyWith(
            fontWeight: FontWeight.w500,
          ),
        ),
        const SizedBox(height: 8),
        Wrap(
          spacing: 8,
          runSpacing: 8,
          children: [
            '720p', '1080p', '4K', '8K'
          ].map((resolution) => FilterChip(
            label: Text(resolution),
            selected: _filter.selectedResolutions.contains(resolution),
            onSelected: (selected) {
              setState(() {
                if (selected) {
                  _filter.selectedResolutions.add(resolution);
                } else {
                  _filter.selectedResolutions.remove(resolution);
                }
              });
              _updateFilter();
            },
          )).toList(),
        ),
      ],
    );
  }
}

// 筛选区域组件
class _FilterSection extends StatelessWidget {
  final String title;
  final Widget child;

  const _FilterSection({
    required this.title,
    required this.child,
  });

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          title,
          style: Theme.of(context).textTheme.titleSmall?.copyWith(
            fontWeight: FontWeight.bold,
          ),
        ),
        const SizedBox(height: 12),
        child,
      ],
    );
  }
}

// 媒体筛选器类
class MediaFilter {
  bool showImages;
  bool showVideos;
  Set<String> selectedExtensions;
  Set<String> selectedResolutions;
  RangeValues? focalLengthRange;
  RangeValues? apertureRange;
  RangeValues? isoRange;
  RangeValues? durationRange;

  MediaFilter({
    this.showImages = true,
    this.showVideos = true,
    Set<String>? selectedExtensions,
    Set<String>? selectedResolutions,
    this.focalLengthRange,
    this.apertureRange,
    this.isoRange,
    this.durationRange,
  }) : selectedExtensions = selectedExtensions ?? {},
       selectedResolutions = selectedResolutions ?? {};

  MediaFilter copy() {
    return MediaFilter(
      showImages: showImages,
      showVideos: showVideos,
      selectedExtensions: Set.from(selectedExtensions),
      selectedResolutions: Set.from(selectedResolutions),
      focalLengthRange: focalLengthRange,
      apertureRange: apertureRange,
      isoRange: isoRange,
      durationRange: durationRange,
    );
  }

  bool get hasActiveFilters {
    return selectedExtensions.isNotEmpty ||
           selectedResolutions.isNotEmpty ||
           focalLengthRange != null ||
           apertureRange != null ||
           isoRange != null ||
           durationRange != null ||
           !showImages ||
           !showVideos;
  }
}